package com.java8.Stream;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

//收集
public class demo05_终止方法_2 {
    @Test
    public void test1() {
        //Collectors.toList() : 在底层会创建一个List集合.并把所有的数据添加到List集合中.
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> nums = numbers.stream()
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toList());
        System.out.println(nums);//[2, 4]
        //Collectors.toSet()
        Set<Integer> nums2 = numbers.stream()
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toSet());
        System.out.println(nums2);
    }
    @Test
    public void test2() {
        //Stream流的收集方法 toMap方法演示
        ArrayList<String> list = new ArrayList<>();
        list.add("zhangsan,23");
        list.add("lisi,24");
        list.add("wangwu,25");
        //[zhangsan,23, lisi,24, wangwu,25]
        System.out.println(list);
        Map<String, Integer> map = list.stream()
                .filter(
                        s -> {
                            String[] split = s.split(",");
                            int age = Integer.parseInt(split[1]);
                            return age >= 24;
                        }
                ).collect(Collectors.toMap(
                        s -> s.split(",")[0], //key
                        s -> Integer.parseInt(s.split(",")[1])));//val);
        System.out.println(map);
        //当然也可以先将字符串解析为临时对象（map），提升效率：
        System.out.println("-----------");
        Map<String, Integer> map2 = list.stream()
                .map(s -> s.split(","))
                .filter(str -> Integer.parseInt(str[1]) >= 24)
                .collect(Collectors.toMap(
                        str -> str[0],
                        str -> Integer.parseInt(str[1])
                ));
        System.out.println(map2);

    }
    
}
